//
//  MessageViewController.swift
//  Swift_SendMessage
//
//  Created by lanou on 15/11/25.
//  Copyright © 2015年 changfengZhang. All rights reserved.
//

import UIKit

class MessageViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    //在Swift的项目中最好使用OC的数组
    var dataArray : NSMutableArray  = NSMutableArray()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        //预估高度
        self.tableView.estimatedRowHeight = 100
        self.tableView.rowHeight = UITableViewAutomaticDimension
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发微博", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("sendBarButtonClicked"))
        
        self.loadData()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
        
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MessageTableViewCell
        
        let object = self.dataArray[indexPath.row] as! PFObject
        
        cell.label.text = object.objectForKey("message") as? String
        
        return cell
    }
   
    func sendBarButtonClicked() {
        
        let sendVC = UIStoryboard(name: "Main", bundle: nil) .instantiateViewControllerWithIdentifier("sendVC") as! SendViewController
        
        sendVC.result = { () -> Void in
            
            self.loadData()
            
        }
        
        self.navigationController?.pushViewController(sendVC, animated: true)
    }
    
    func loadData() {
        
        let quary = PFQuery(className : "Yan30MyMessage")
        
        quary.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            
            if error == nil {
                
                self.dataArray.setArray(objects!)
                
                self.tableView.reloadData()
                
            }
            
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
